package com.lonely.goods.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lonely.common.core.domain.TimeLine;
import com.lonely.common.enums.CommonStatus;
import com.lonely.common.utils.SecurityUtils;
import com.lonely.goods.domain.entity.SysMaterialLog;
import com.lonely.goods.mapper.SysMaterialLogMapper;
import com.lonely.goods.service.IMaterialLogService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : 黄志标
 * @date: 2025/8/26 10:35
 * @description: 物料日志服务实现类
 */
@Service
public class MaterialLogServiceImpl extends ServiceImpl<SysMaterialLogMapper, SysMaterialLog> implements IMaterialLogService {

    /**
     * 添加日志
     *
     * @param materialId
     * @param title
     * @param body
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addLog(Long materialId, String title, String body) {
        SysMaterialLog sysMaterialLog = new SysMaterialLog();
        sysMaterialLog.setMaterialId(materialId);
        sysMaterialLog.setLogTitle(title);
        sysMaterialLog.setLogBody(body);
        sysMaterialLog.setCreateBy(SecurityUtils.getUserId());
        sysMaterialLog.setUpdateBy(SecurityUtils.getUserId());
        super.save(sysMaterialLog);
    }

    /**
     * 获取指定物料采购单的日志时间线
     *
     * @param materialId
     * @return
     */
    @Override
    public List<TimeLine> getLogTimeLine(Long materialId) {
        return super.list(new LambdaQueryWrapper<SysMaterialLog>()
                        .eq(SysMaterialLog::getMaterialId, materialId)
                        .eq(SysMaterialLog::getStatus, CommonStatus.ENABLE.code)
                        .orderByDesc(SysMaterialLog::getCreateTime))
                .stream().map(currentMaterialPurchaseLog -> {
                    TimeLine timeLine = new TimeLine();
                    timeLine.setType("info");
                    timeLine.setContent(currentMaterialPurchaseLog.getLogBody());
                    timeLine.setTitle(currentMaterialPurchaseLog.getLogTitle());
                    timeLine.setTime(DateUtil.formatDateTime(currentMaterialPurchaseLog.getCreateTime()));
                    return timeLine;
                }).collect(Collectors.toList());
    }
}
